import Vue from 'vue'
import Router from 'vue-router'
import login from '@/components/login'
import home from '@/components/home/home'
import welcome from '@/components/home/welcome'
import userlist from '@/components/users/userlist'

Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/login', component: login, name: 'login' },
    {
      path: '/home',
      component: home,
      redirect: '/welcome',
      name: 'home',
      children: [{ path: '/welcome', component: welcome }, { path: '/users', component: userlist }]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const tokenstr = window.sessionStorage.getItem('token')
  if (!tokenstr) return next('/login')
  next()
})

export default router
